package cn.com.anypay.manager.miaoma.suantaiqrcode.handler.impl;

import cn.com.anypay.manager.miaoma.suantaiqrcode.SuantaiQrcodeEntity;
import cn.com.anypay.manager.miaoma.suantaiqrcode.handler.AbstractQrCodeHandler;
import cn.com.anypay.manager.common.response.ApiResponse;
import com.fasterxml.jackson.databind.JsonNode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * 群码类型二维码处理器 (type = 9)
 * 支持主群二维码和备用群二维码，完全走网关模式
 */
@Slf4j
@Component
public class GroupQrCodeHandler extends AbstractQrCodeHandler {
    private static final Integer SUPPORTED_TYPE = 9;
    private static final String HANDLER_NAME = "GroupQrCodeHandler";

    @Override
    public ApiResponse<Object> handle(SuantaiQrcodeEntity qrcode, String id) {
        // 只支持网关模式
        return createErrorResponse(HttpStatus.BAD_REQUEST, "群码类型仅支持网关模式");
    }

    @Override
    public ApiResponse<Object> handleForGateway(SuantaiQrcodeEntity qrcode, String id) {
        logHandleStart(id);
        if (!isValidContent(qrcode.getContent())) {
            logHandleComplete(id, "Content is empty");
            return createErrorResponse(HttpStatus.BAD_REQUEST, "Content is empty");
        }
        JsonNode content = parseJsonContent(qrcode.getContent());
        if (content == null) {
            logHandleComplete(id, "Failed to parse JSON content");
            return createErrorResponse(HttpStatus.BAD_REQUEST, "Invalid JSON content");
        }
        // 结构化返回主群和备用群二维码图片及描述
        Map<String, Object> groupData = new HashMap<>();
        groupData.put("mainGroupImage", content.has("mainGroupImage") ? content.get("mainGroupImage").asText() : "");
        groupData.put("mainGroupTitle", content.has("mainGroupTitle") ? content.get("mainGroupTitle").asText() : "主群二维码");
        groupData.put("mainGroupDesc", content.has("mainGroupDesc") ? content.get("mainGroupDesc").asText() : "扫码进主群");
        groupData.put("backupGroupImage", content.has("backupGroupImage") ? content.get("backupGroupImage").asText() : "");
        groupData.put("backupGroupTitle", content.has("backupGroupTitle") ? content.get("backupGroupTitle").asText() : "备用群二维码");
        groupData.put("backupGroupDesc", content.has("backupGroupDesc") ? content.get("backupGroupDesc").asText() : "主群已满可加备用群");
        logHandleComplete(id, "返回群码结构化数据");
        return createGatewayDisplayResponse(
            qrcode.getQrCodeId(),
            qrcode.getQrCodeName(),
            SUPPORTED_TYPE,
            "group", // displayData.type
            groupData.toString(), // content 字段传字符串
            qrcode.getQrCodeName(),
            qrcode.getDescription(),
            groupData // metadata 传递所有字段
        );
    }

    @Override
    public Integer getSupportedType() {
        return SUPPORTED_TYPE;
    }

    @Override
    public String getHandlerName() {
        return HANDLER_NAME;
    }
} 